package com.lxw.question;

import java.util.Arrays;

public class Q25 {

    /**
     * 重建二叉树
     */

    public TreeNode buildTree(int[] preorder, int[] inorder) {

        int length = preorder.length;

        if(length == 0) {
            return null;
        }

        int rootValue = preorder[0],rootIndex = 0;

        for(int i = 0 ; i < length ; i++){
            if(inorder[i] == rootValue){
                rootIndex = i;
                break;
            }
        }

        TreeNode root = new TreeNode(rootValue);

        root.left = buildTree(Arrays.copyOfRange(preorder,1,1 + rootIndex),Arrays.copyOfRange(inorder,0,rootIndex));
        root.right = buildTree(Arrays.copyOfRange(preorder,1+rootIndex,length),Arrays.copyOfRange(inorder,rootIndex+1,length));

        return root;
    }
}
